package com.xry.test1.service.impl;


import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


@Service
public class DeviceStatusService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceStatusService.class);

    @Autowired
    private LightService lightService;

    @Autowired
    private FanServiceImpl fanServiceImpl;

    @Autowired
    private MQTTSubscribe mqttSubscribe;

    private Integer lastFanLevel = 0;
    private String lastLightState = "000";
    //private String lastLightState = "";

    /**
     * 获取设备的状态并拼接成四位数字发送到MQTT
     */
    public void checkAndUpdateDeviceStatus() {
        //System.out.println("————————————————————————————————————————");
        Integer currentFanLevel = fanServiceImpl.getLastFanLevel();
        //System.out.println("currentFanLevel+++"+currentFanLevel);
        String currentLightState = lightService.getLastLight();
        //System.out.println("currentLightState+++"+currentLightState);

        // 如果风扇状态变化，拼接并发送四位数字
        if (!currentFanLevel.equals(lastFanLevel) || !currentLightState.equals(lastLightState)) {
            String statusMessage = buildStatusMessage(currentFanLevel, currentLightState);
            System.out.println("D中；拼接数据————————————————"+statusMessage);
            mqttSubscribe.sendMQTTMessage("bedroom_cmd", statusMessage, 2);  // 发布到 bedroom_cmd 主题
            lastFanLevel = currentFanLevel;
            lastLightState = currentLightState;
        }
    }


    /**
     * 拼接风扇和灯光的状态，生成四位数字
     * 例如：风扇挡位 1，灯光状态 1，结果为 "0101"
     */
    private String buildStatusMessage(Integer fanLevel,String lightState) {
        String fanStatus = fanLevel.toString();  // 格式化为1位数字
        return fanStatus + lightState;
    }

    @Scheduled(fixedRate = 500)  // 每半秒执行一次
    public void checkAndUpdateDeviceStatusScheduled() {
        checkAndUpdateDeviceStatus();  // 定期检查设备状态并更新
    }


}

